import { PropsWithChildren, useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { PlayCircleOutlined } from "@ant-design/icons";

import "./styles.sass";
import { Hero } from "@/shared/typicode/models";
import { AppDispatch } from "@/shared/typicode/heroes";
import { useDispatch } from "react-redux";
import { heroesActions } from "@/entities/heroes/model";

export type HeroRowProps = PropsWithChildren<{
  data: Hero;
}>;

// тут по клику навигация

export const HeroRow = ({ data }: HeroRowProps) => {
  const [heroId, setHeroId] = useState<string | null>(null);
  const dispatch = useDispatch<AppDispatch>();

  const handleClick = () => {
    dispatch(heroesActions["addHistory"]({ id: heroId, name: data.name }));
  };

  useEffect(() => {
    const match = data.url?.match(/\d+/g);
    if (match && match[0]) {
      setHeroId(match[0]);
    }
  }, [data]);

  return (
    <Link to={`/${heroId}`} className="hero-row" onClick={() => handleClick()}>
      <PlayCircleOutlined style={{ fontSize: "1.5em", color: "#ffe81f" }} />
      <div>{data.name}</div>
    </Link>
  );
};
